package com.etc.traval.servlet;

import java.io.IOException;

import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.etc.traval.biz.ComplaintBiz;
import com.etc.traval.biz.OrderBiz;
import com.etc.traval.biz.UserBiz;
import com.etc.traval.bizimpl.ComplaintBizImpl;
import com.etc.traval.bizimpl.OrderBizImpl;
import com.etc.traval.bizimpl.UserBizImpl;
import com.etc.traval.pojo.SellerPojo;
import com.etc.traval.pojo.UserMoneyPojo;
import com.etc.traval.util.JDBCUtil;
import com.etc.traval.util.MyUtil;
import com.etc.travel.entity.Complaint;
import com.etc.travel.entity.Order;
import com.etc.travel.entity.User;
import com.google.gson.Gson;

public class UserServlet extends HttpServlet {

	/**
		 * Constructor of the object.
		 */
	public UserServlet() {
		super();
	}

	/**
		 * Destruction of the servlet. <br>
		 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
		 * The doGet method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to get.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String flag=request.getParameter("flag");
		//将登录的用户保存到session域中
		
		if(flag.equals("login")){
		String userid=request.getParameter("userid");
		String pwd=request.getParameter("userpwd");
		UserBiz userbiz=new UserBizImpl();
		PrintWriter out=response.getWriter();
		User user=userbiz.UserLogin(Integer.parseInt(userid), pwd);
		if(user==null){
		out.println("<script>alert('登录失败，您的用户ID或密码错误，点击重新登录');location.href='login.jsp'</script>");
		}
		else{
			
		    if(user.getUser_status().equals("管理员")){
		    	HttpSession session=request.getSession();
			    session.setAttribute("admin", user);
		    	out.print("<script>alert('管理员登录成功');location.href='admin.jsp';</script>");
		    }else {
		    	HttpSession session=request.getSession();
			    session.setAttribute("user", user);
			out.println("<script>alert('登入成功');location.href='DiaryServlet?flag=toindex'</script>");
		    }
		}
 
        out.flush();
        out.close();
		}
		//退出登录
		else if(flag.equals("loginout")){
			//退出登录的servlet
			//将session设置失效
			request.getSession().invalidate();
			response.sendRedirect("DiaryServlet?flag=toindex");
		}
		//注册
		else if(flag.equals("register")){
			String username=request.getParameter("username");
			String userpwd=request.getParameter("userpwd");
			String usertel=request.getParameter("usertel");
			String usersex=request.getParameter("usersex");
			UserBiz biz=new UserBizImpl();
			User user=new User();
			user.setUser_name(username);
			user.setUser_pwd(userpwd);
			user.setUser_tel(usertel);
			user.setUser_sex(usersex);
			user.setUser_status("用户");
			user.setUser_money(0.0);
			user.setUser_logo("imgage/userlogo0");
			PrintWriter out=response.getWriter();
			if(1==biz.checktel(usertel)){
				out.print("<script>alert('注册失败，此号码已经被注册了');location.href='register.jsp';</script>");
			}else{
			if(biz.UserRegister(user)){
				request.getSession().setAttribute("user", user);
				User user1=biz.queryUserByTel(usertel);
				int userid=user1.getUser_id();
			out.println("<script>alert('注册成功，恭喜你成为我们大家庭的一员，你的煤块号为："+userid+"');location.href='login.jsp';</script>");
			}else{
		    out.println("<script>alert('注册失败');location.href='register.jsp';</script>");

			}
			}
			out.flush();
			out.close();
			}
		
		//修改密码
		else if(flag.equals("updatepwd")){
			String pwd1=request.getParameter("oldpwd");
			String pwd2=request.getParameter("newpwd");
			HttpSession session =request.getSession();
			User user=(User) session.getAttribute("user");
			String mypwd=user.getUser_pwd();
			UserBiz biz=new UserBizImpl();
			PrintWriter out=response.getWriter();
			if(mypwd.equals(pwd1)){
			if(biz.updatePwdById(user.getUser_id(), pwd1, pwd2)){
				out.print("<script>alert('密码已修改,请重新登录');location.href='login.jsp'</script>");
			}else{
				out.print("<script>alert('修改失败');location.href='updatepwd.jsp'</script>");
			}
			}else{ 
				out.print("<script>alert('修改失败，原密码错误');location.href='updatepwd.jsp'</script>");
			}
			out.flush();
			out.close();
		}
		
		//显示对应用户全部的订单
		else if(flag.equals("queryorderbyuser")){
			OrderBiz obiz=new OrderBizImpl();
			User user=(User) request.getSession().getAttribute("user");
			List<Order> list=obiz.queryByUser(user);
			Gson gson=new Gson();
		    String jsonString= gson.toJson(list);
		    response.setContentType("text/html;charset=utf-8");;
		    PrintWriter out = response.getWriter();
		    out.print(jsonString);
		    out.flush();
		    out.close(); 
			
			
		}
		//充值
		else if(flag.equals("addmoney")){
			UserBiz biz=new UserBizImpl();
			String usertel=request.getParameter("settel");
			double addmoney=Double.parseDouble(request.getParameter("setmoney"));
			PrintWriter out=response.getWriter();
			User user=biz.queryUserByTel(usertel);
			if(usertel.equals(null)||addmoney<=0||usertel.equals("")){
				out.print("<script>alert('输入信息有误');location.href='addmoney.jsp'</script>");
			}else{
			    biz.addUserMoneyById(user.getUser_id(),addmoney);
				HttpSession session =request.getSession();
				User user1 = (User) session.getAttribute("user");
				double oldmoney = user1.getUser_money();
				user1.setUser_money(oldmoney+ addmoney);
			    session.setAttribute("user",user1);
				out.print("<script>alert('充值成功');location.href='userinfo.jsp'</script>");
			}    
			out.flush();
		    out.close(); 
		}
		
		//提现
		else if(flag.equals("upmoney")){
			UserBiz biz=new UserBizImpl();
			double downmoney=Double.parseDouble(request.getParameter("upmoney"));
			PrintWriter out=response.getWriter();
			HttpSession session =request.getSession();
			User user=(User) session.getAttribute("user");
			if(downmoney<=0){
				out.print("<script>alert('输入金额格式不对');location.href='upmoney.jsp'</script>");
			}else{
				if(downmoney>user.getUser_money()){
					out.print("<script>alert('亲爱的煤块，您并没有那么多钱');location.href='upmoney.jsp'</script>");
				}else{
					biz.reduceUserMoneyById(user.getUser_id(), downmoney);
					HttpSession session1 =request.getSession();
					User user1 = (User) session1.getAttribute("user");
					double oldmoney=user1.getUser_money();
					user.setUser_money(oldmoney-downmoney);
				    session.setAttribute("user",user1);
				    out.print("<script>alert('提现成功');location.href='userinfo.jsp'</script>");
				}
			}
			out.flush();
		    out.close(); 
		}else if (flag.equals("getmoneypojo")) {
			JDBCUtil util = new JDBCUtil();
			int userid = Integer.parseInt(request.getParameter("userid"));
			UserMoneyPojo userMoneyPojo = new UserMoneyPojo();
			ResultSet rs1=util.query("select sum(order_money) as money from t_order where order_endtime like '%1月%' and order_user=?",userid);
			ResultSet rs2=util.query("select sum(order_money) as money from t_order where order_endtime like '%2月%' and order_user=?",userid);
			ResultSet rs3=util.query("select sum(order_money) as money from t_order where order_endtime like '%3月%' and order_user=?",userid);
			ResultSet rs4=util.query("select sum(order_money) as money from t_order where order_endtime like '%4月%' and order_user=?",userid);
			ResultSet rs5=util.query("select sum(order_money) as money from t_order where order_endtime like '%5月%' and order_user=?",userid);
			ResultSet rs6=util.query("select sum(order_money) as money from t_order where order_endtime like '%6月%' and order_user=?",userid);
			try {
				if(rs1.next()){
					userMoneyPojo.setJan(rs1.getDouble("money"));
				}else {
					userMoneyPojo.setJan(0);
				}
				if(rs2.next()){
					userMoneyPojo.setFed(rs2.getDouble("money"));
				}else {
					userMoneyPojo.setFed(0);
				}
				if(rs3.next()){
					userMoneyPojo.setMar(rs3.getDouble("money"));
				}else {
					userMoneyPojo.setMar(0);
				}
				if(rs4.next()){
					userMoneyPojo.setApr(rs4.getDouble("money"));
				}else {
					userMoneyPojo.setApr(0);
				}
				if(rs5.next()){
					userMoneyPojo.setMay(rs5.getDouble("money"));
				}else {
					userMoneyPojo.setMay(0);
				}
				if(rs6.next()){
					userMoneyPojo.setJun(rs6.getDouble("money"));
				}else {
					userMoneyPojo.setJun(0);
				}
			}catch (SQLException e) {
				e.printStackTrace();
			}finally {
				util.closeAll();
			}
			Gson gson=new Gson();
		    String jsonString= gson.toJson(userMoneyPojo);
		    response.setContentType("text/html;charset=utf-8");;
		    PrintWriter out = response.getWriter();
		    out.print(jsonString);
		    out.flush();
		    out.close();
		}
		//用户投诉
		else if(flag.equals("comp")){
			HttpSession session =request.getSession();
			User user=(User) session.getAttribute("user");
			PrintWriter out=response.getWriter();
			String usercomp=request.getParameter("usercomp");
			if(usercomp==null||usercomp==""){
				out.print("<script>alert('投诉内容不能为空');location.href='comp.jsp'</script>");
			}else{
			Complaint comp=new Complaint();
			comp.setComplaint_status("未审核");
			comp.setComplaint_user(user);
			comp.setComplaint_content(usercomp);
			comp.setComplaint_time(MyUtil.getWebsiteDatetime());
			ComplaintBiz biz=new ComplaintBizImpl();
			if(biz.addComplaint(comp)){
				out.print("<script>alert('投诉成功');location.href='compsuccess.jsp'</script>");
			}else{
				out.print("<script>alert('投诉失败');location.href='comp.jsp'</script>");
			}
			}
		out.flush();
	    out.close(); 
		}
		//忘记密码了
		else if(flag.equals("forgetpwd")){
			String tel=request.getParameter("usertel");
			String pwd1=request.getParameter("newpwd");
			UserBiz biz=new UserBizImpl();
			PrintWriter out=response.getWriter();
			User user=biz.queryUserByTel(tel);
			if(user.getUser_name()==null||user.getUser_name()==""){
				out.print("<script>alert('用户不存在');location.href='forgetpwd.jsp'</script>");
			}else{
			if(biz.updatePwdById(user.getUser_id(), pwd1)){
				out.print("<script>alert('重置成功');location.href='login.jsp'</script>");
			}else{
				out.print("<script>alert('重置失败');location.href='login.jsp'</script>");
			}
			}
			out.flush();
			out.close();
			
			
		}
		
		
		}
		
	

	/**
		 * The doPost method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to post.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	/**
		 * Initialization of the servlet. <br>
		 *
		 * @throws ServletException if an error occurs
		 */
	public void init() throws ServletException {
		// Put your code here
	}

}
